package com.shqcjd.yunweiyanoperator.ui.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.google.gson.Gson;
import com.orhanobut.logger.Logger;
import com.shqcjd.yunweiyanoperator.R;
import com.shqcjd.yunweiyanoperator.api.ApiService;
import com.shqcjd.yunweiyanoperator.helper.rxjavahelper.RxObserver;
import com.shqcjd.yunweiyanoperator.helper.rxjavahelper.RxSchedulersHelper;
import com.shqcjd.yunweiyanoperator.model.ResponseData;
import com.shqcjd.yunweiyanoperator.model.eventbus.CompanyRegisterSuccessEvebt;
import com.shqcjd.yunweiyanoperator.model.eventbus.WechatLoginEvent;
import com.shqcjd.yunweiyanoperator.model.pojo.MajorBean;
import com.shqcjd.yunweiyanoperator.model.pojo.RegisterRequest;
import com.shqcjd.yunweiyanoperator.ui.base.BaseActivity;
import com.shqcjd.yunweiyanoperator.ui.base.BasePresenter;
import com.shqcjd.yunweiyanoperator.util.ToastUtils;
import com.shqcjd.yunweiyanoperator.util.UIUtils;
import com.shqcjd.yunweiyanoperator.widget.LoginTipsDialog;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.BindView;
import butterknife.OnClick;

public class PersonalRegisterActivity extends BaseActivity {
    @BindView(R.id.et_register_personal_phone)
    EditText etRegisterPersonalPhone;
    @BindView(R.id.tl_register_personal_phone)
    TextInputLayout tlRegisterPersonalPhone;
    @BindView(R.id.et_register_personal_pwd)
    EditText etRegisterPersonalPwd;
    @BindView(R.id.et_register_personal_pwd_true)
    EditText etRegisterPersonalPwdTrue;
    @BindView(R.id.tl_register_personal_pwd)
    TextInputLayout tlRegisterPersonalPwd;
    @BindView(R.id.tv_register_personal_next)
    TextView tvRegisterPersonalNext;
    @BindView(R.id.tv_register_personal_code)
    TextView tvRegisterPersonalCode;
    @BindView(R.id.et_register_personal_name)
    EditText etRegisterPersonalName;
    @BindView(R.id.et_register_personal_code)
    EditText etRegisterPersonalCode;
//    @BindView(R.id.et_register_personal_info)
//    EditText etRegisterPersonalInfo;
    @BindView(R.id.tv_register_personal_company)
    TextView tvRegisterPersonalCompany;
    @BindView(R.id.tl_register_personal_name)
    TextInputLayout tlRegisterPersonalName;
    @BindView(R.id.tl_register_personal_code)
    TextInputLayout tlRegisterPersonalCode;
    @BindView(R.id.tl_register_personal_info)
    TextInputLayout tlRegisterPersonalInfo;
    @BindView(R.id.btn_finish)
    ImageView btnFinish;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_specialty)
    TextView tv_specialty;

    private String mCode = "-1";
    private Context mContext;
    private final int CODE_TIME = 1000;
    private int codeNum = 60;
    private String businessId = "";
    private String codePhone = "";//获取验证码的手机号
    private boolean isWechat = false;

    private Handler codeHandler = new Handler();
    private Runnable codeRunnable = new Runnable() {
        @Override
        public void run() {
            tvRegisterPersonalCode.setText("还剩" + codeNum + "秒");
            if (codeNum == 1) {
                tvRegisterPersonalCode.setText("获取");
                codeHandler.removeCallbacks(codeRunnable);
            } else {
                codeNum--;
                codeHandler.postDelayed(codeRunnable, CODE_TIME);
            }
        }
    };
    private List<Integer> majorIds;


    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_personal_register;
    }

    @Override
    public void init() {
        super.init();
        mContext = this;
        isWechat = getIntent().getBooleanExtra("isWechat", false);
    }

    @Override
    public void initView() {
        super.initView();
        EventBus.getDefault().register(this);
        if (isWechat) {
            tvTitle.setText("绑定个人信息");
            etRegisterPersonalName.setText(LoginActivity.wechatName);
        } else {
            tvTitle.setText("注册");
        }
        btnFinish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        etRegisterPersonalPwdTrue.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                password();
            }
        });


        addListener(tlRegisterPersonalPhone, etRegisterPersonalPhone, "手机号不能为空");
        addListener(tlRegisterPersonalName, etRegisterPersonalName, "姓名不能为空");
        addListener(tlRegisterPersonalCode, etRegisterPersonalCode, "验证码不能为空");
//        addListener(tlRegisterPersonalInfo, etRegisterPersonalInfo, "维护信息不能为空");
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onFinishCompanyRegisterEvent(CompanyRegisterSuccessEvebt event) {
        String name = event.name;
        businessId = event.companyId;
        tvRegisterPersonalCompany.setText(name);
        tvRegisterPersonalCompany.setTextColor(Color.parseColor("#4D5576"));
    }

    private void addListener(TextInputLayout textInputLayout, EditText editText, String str) {
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                notNull(textInputLayout, editText, str);
            }
        });
    }

    private boolean notNull(TextInputLayout textInputLayout, EditText editText, String str) {
        if (TextUtils.isEmpty(editText.getText().toString().trim())) {
            textInputLayout.setError(str);
            return false;
        } else {
            textInputLayout.setError(null);
            textInputLayout.setErrorEnabled(false);

        }
        return true;
    }

    private boolean password() {
        if (etRegisterPersonalPwdTrue.getText().toString().length() >= etRegisterPersonalPwd.getText().toString().length() && !etRegisterPersonalPwdTrue.getText().toString().equals(etRegisterPersonalPwd.getText().toString())) {
            tlRegisterPersonalPwd.setError("密码不一致");
            return false;
        } else {
            tlRegisterPersonalPwd.setError(null);
            tlRegisterPersonalPwd.setErrorEnabled(false);

        }
        return true;
    }


    @OnClick({R.id.tv_register_personal_code, R.id.tv_register_personal_next, R.id.tv_register_personal_company, R.id.tv_specialty})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_register_personal_code:
                if (tvRegisterPersonalCode.getText().toString().equals("获取")) {
                    if (UIUtils.isMobile(etRegisterPersonalPhone.getText().toString())) {
                        codeNum = 60;
                        codeHandler.postDelayed(codeRunnable, 1);
                        codePhone = etRegisterPersonalPhone.getText().toString();
                        getCodeHttp(etRegisterPersonalPhone.getText().toString());
                    } else {
                        ToastUtils.showShort(mContext, "请输入正确的手机号");
                    }
                }
                break;
            case R.id.tv_register_personal_next:
                if (!isNull()) {
                    if (etRegisterPersonalCode.getText().toString().equals(mCode)) {
                        if (etRegisterPersonalPwd.getText().toString().equals(etRegisterPersonalPwdTrue.getText().toString())) {
                            if (etRegisterPersonalPwdTrue.getText().toString().trim().length() >= 6) {
                                if (codePhone.equals(etRegisterPersonalPhone.getText().toString().trim())) {
                                    if(isWechat){
                                        personalWechatRegisterHttp();
                                    }else{
                                        personalRegisterHttp();
                                    }
                                } else {
                                    ToastUtils.showShort(mContext, "输入的手机号有误");
                                }
                            } else {
                                ToastUtils.showShort(mContext, "密码必须大于等于6位");
                            }
                        } else {
                            ToastUtils.showShort(mContext, "密码不一致");
                        }
                    } else {
                        ToastUtils.showShort(mContext, "验证码有误");
                    }
                } else {
                    ToastUtils.showShort(mContext, "请确认所有信息填写完毕");
                }
                break;
            case R.id.tv_register_personal_company:
                Intent it = new Intent(mContext, CompanyActivity.class);
                startActivityForResult(it, 110);
                break;
            case R.id.tv_specialty://选择专业
                showSpecialtyDialog();
                break;
        }
    }

    private void personalRegisterHttp() {
//        Map<String, String> map = new HashMap<>();
//        map.put("businessId", businessId);
//        map.put("maintainInfo", etRegisterPersonalInfo.getText().toString().trim());
//        map.put("password", etRegisterPersonalPwdTrue.getText().toString().trim());
//        map.put("phoneNumber", etRegisterPersonalPhone.getText().toString().trim());
//        map.put("userName", etRegisterPersonalName.getText().toString().trim());
//        map.put("verificationCode", etRegisterPersonalCode.getText().toString().trim());
//        if (isWechat) {
//            map.put("verificationCode", etRegisterPersonalCode.getText().toString().trim());
//        }
        RegisterRequest register = new RegisterRequest();
        register.businessId = businessId;
        register.password = etRegisterPersonalPwdTrue.getText().toString().trim();
        register.phoneNumber = etRegisterPersonalPhone.getText().toString().trim();
        register.userName = etRegisterPersonalName.getText().toString().trim();
        register.verificationCode = etRegisterPersonalCode.getText().toString().trim();
//        if (isWechat) {
//            register.verificationCode = etRegisterPersonalCode.getText().toString().trim();
//        }
        register.majorIds = majorIds;



//        String encrypt = RSAUtils.encrypt(RSAUtils.PUCLIC_KEY, new JSONObject(map).toString());
        ApiService.personalRegister(new Gson().toJson(register))
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData>() {

                    @Override
                    public void _onNext(ResponseData retData) {
                        if (retData != null && retData.retCode == 10000) {
                            LoginTipsDialog loginDialog = new LoginTipsDialog(mContext);
                            loginDialog.show();
                            loginDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                                @Override
                                public void onDismiss(DialogInterface dialog) {
                                    Intent it = new Intent(mContext, LoginActivity.class);
                                    it.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                    startActivity(it);
                                }
                            });
                        } else {
                            ToastUtils.showShort(mContext, retData.retMsg);
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        ToastUtils.showShort(mContext, errorMessage);
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                    }
                });
    }


    private void personalWechatRegisterHttp() {
        RegisterRequest register = new RegisterRequest();
        register.businessId = businessId;
        register.password = etRegisterPersonalPwdTrue.getText().toString().trim();
        register.phoneNumber = etRegisterPersonalPhone.getText().toString().trim();
        register.userName = etRegisterPersonalName.getText().toString().trim();
        register.verificationCode = etRegisterPersonalCode.getText().toString().trim();
        register.openId  = LoginActivity.wechatOpenid;
        register.majorIds = majorIds;
        ApiService.wechatRegister(new Gson().toJson(register))
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData>() {

                    @Override
                    public void _onNext(ResponseData retData) {
                        if (retData != null && retData.retCode == 10000) {
                            LoginTipsDialog loginDialog = new LoginTipsDialog(mContext);
                            loginDialog.show();
                            loginDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                                @Override
                                public void onDismiss(DialogInterface dialog) {
                                    Intent it = new Intent(mContext, LoginActivity.class);
                                    it.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                    startActivity(it);
                                        EventBus.getDefault().post(new WechatLoginEvent());
                                }
                            });
                        } else {
                            ToastUtils.showShort(mContext, retData.retMsg);
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        ToastUtils.showShort(mContext, errorMessage);
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                    }
                });
    }


    private boolean isNull() {
        if (!etRegisterPersonalPhone.getText().toString().equals("") && !etRegisterPersonalPwd.getText().toString().equals("") &&
                !etRegisterPersonalPwdTrue.getText().toString().equals("") && !etRegisterPersonalName.getText().toString().equals("") &&
                !etRegisterPersonalCode.getText().toString().equals("") &&
                !tv_specialty.getText().toString().equals("")) {
            return false;
        }
        if(!isWechat&&!businessId.equals("")){
            return false;
        }
        return true;
    }

    private void getCodeHttp(String phone) {
        Map<String, String> map = new HashMap<>();
        map.put("phoneNumber", phone);
//        String encrypt = RSAUtils.encrypt(RSAUtils.PUCLIC_KEY, new JSONObject(map).toString());
        String json = new JSONObject(map).toString();
        ApiService.getCode(json)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<String>>() {

                    @Override
                    public void _onNext(ResponseData<String> retData) {
                        if (retData != null && retData.retCode == 10000) {
                            mCode = retData.data;
                        } else {
                            ToastUtils.showShort(mContext, retData.retMsg);
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        ToastUtils.showShort(mContext, errorMessage);
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                    }
                });
    }

    ArrayList<String> mTypeVals = new ArrayList<>();
    private ArrayList<Integer> mTypeId = new ArrayList<>();

    /**
     * 显示选择专业
     */
    private void showSpecialtyDialog() {
        final MaterialDialog dialog = new MaterialDialog.Builder(this)
                .customView(R.layout.custome_specialty_layout, false)
                .show();
        dialog.getWindow().setBackgroundDrawableResource(R.color.transparent);
        View customeView = dialog.getCustomView();

        TagFlowLayout specialty = customeView.findViewById(R.id.flowlayout_specialty);
        Button btn_confirm = customeView.findViewById(R.id.btn_confirm);

        getMajor(specialty);

        btn_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Set<Integer> selectedList = specialty.getSelectedList();
                List<String> typeList = new ArrayList<>();
                for (Integer integer : selectedList) {
                    typeList.add(mTypeVals.get(integer));
                }
                String content = typeList.toString().replace("[", "").replace("]", "");
                tv_specialty.setText(content);

                List<Integer> ids = new ArrayList<>();
                for (Integer integer : selectedList) {
                    ids.add(mTypeId.get(integer));
                }
                majorIds = ids;

                Logger.i("类型:" + majorIds.toString());

                dialog.dismiss();
            }
        });
    }

    private void getMajor(TagFlowLayout view) {
        ApiService.getMajor()
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<List<MajorBean>>>() {
                    @Override
                    public void _onNext(ResponseData<List<MajorBean>> retData) {
                        if (retData.retCode == 10000) {
                            mTypeVals.clear();
                            mTypeId.clear();
                            for (MajorBean majorBean : retData.data) {
                                mTypeVals.add(majorBean.name);
                                mTypeId.add(majorBean.id);
                            }

                            TagAdapter tagAdapter = new TagAdapter<String>(mTypeVals.toArray(new String[mTypeVals.size()])) {
                                @Override
                                public View getView(FlowLayout parent, int position, String s) {
                                    TextView tv = (TextView) LayoutInflater.from(mContext).inflate(R.layout.tv_tag,
                                            view, false);
                                    tv.setText(s);
                                    return tv;
                                }

                            };
                            view.setAdapter(tagAdapter);
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {

                    }
                });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 110) {
            String name = data.getStringExtra("name");
            businessId = data.getStringExtra("companyId");
            tvRegisterPersonalCompany.setText(name);
            tvRegisterPersonalCompany.setTextColor(Color.parseColor("#4D5576"));
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
